<script setup lang="ts">
import { ref } from 'vue'
import { mobileRules, passwordRules, codeRules } from '@/utils/rules'
import { showToast } from 'vant'
import { loginByPassword, loginByCode } from '@/services/user'
import { useUserStore } from '@/stores'
import { useRoute, useRouter } from 'vue-router'
import { useSendMobileCode } from '@/composable'

// 1.密码登录
const mobile = ref('')
const password = ref('')
const agree = ref(false)
const route = useRoute() //获取路由参数
const router = useRouter() //跳转路由
const stores = useUserStore()
const login = async () => {
  // 1.1 判断用户是否勾选用户协议
  if (!agree.value) return showToast('请勾选同意用户协议')
  // 1.2 调接口获取用户信息
  const res = isPass.value
    ? await loginByPassword(mobile.value, password.value)
    : await loginByCode(mobile.value, code.value)
  // 1.3 存储用户信息
  stores.setUser(res.data)
  // 1.4 跳转页面
  router.replace((route.query.returnUrl as string) || '/user')
  // 1.5 提示
  showToast('登录成功')
}

// 2.验证码登录
const isPass = ref(true)
const code = ref('')
const { form, time, sendCode } = useSendMobileCode(mobile, 'login')
// const time = ref(0)
// const form = ref<FormInstance>()
// let timerId: number
// const sendCode = async () => {
//   // 2.1 如果 倒计时>0 不能倒计时
//   if (time.value > 0) return
//   // 2.2 校验手机号
//   await form.value?.validate('mobile')
//   // 2.3 获取短信验证码
//   const res = await sendMobileCode(mobile.value, 'login')
//   showToast({
//     message: res.data.code,
//     duration: 5 * 1000
//   })
//   // 2.4 开始倒计时
//   time.value = 60
//   window.clearInterval(timerId)
//   timerId = window.setInterval(() => {
//     time.value--
//     if (time.value <= 0) window.clearInterval(timerId)
//   }, 1000)
// }
// onUnmounted(() => {
//   window.clearInterval(timerId)
// })

// 眼睛
const show = ref(false)

// onMounted(() => {
//   // 组件渲染完毕，使用QC生成QQ登录按钮，目的得到跳转链接
//   QC.Login({
//     btnId: 'qq'
//   })
// })

const qqUrl = `https://graph.qq.com/oauth2.0/authorize?client_id=102015968&response_type=token&scope=all&redirect_uri=${encodeURIComponent(
  import.meta.env.VITE_APP_CALLBACK + '/login/callback'
)}`
</script>

<template>
  <div class="login-page">
    <cp-nav-bar
      right-text="注册"
      @click-right="$router.push('/register')"
    ></cp-nav-bar>
    <!-- 头部 -->
    <div class="login-head">
      <h3>{{ isPass ? '密码登录' : '短信验证码登录' }}</h3>
      <a href="javascript:;" @click="isPass = !isPass">
        <span>{{ !isPass ? '密码登录' : '短信验证码登录' }}</span>
        <van-icon name="arrow"></van-icon>
      </a>
    </div>
    <!-- 表单 -->
    <van-form ref="form" autocomplete="off" @submit="login">
      <van-field
        name="mobile"
        v-model="mobile"
        placeholder="请输入手机号"
        type="tel"
        :rules="mobileRules"
      ></van-field>
      <van-field
        v-if="isPass"
        v-model="password"
        placeholder="请输入密码"
        :type="show ? 'text' : 'password'"
        :rules="passwordRules"
        ><template #right-icon>
          <cp-icon
            @click="show = !show"
            :name="`login-eye-${show ? 'on' : 'off'}`"
          ></cp-icon>
        </template>
      </van-field>
      <van-field
        v-else
        v-model="code"
        placeholder="短信验证码"
        :rules="codeRules"
      >
        <template #button>
          <span
            class="btn-send"
            :class="{ active: time > 0 }"
            @click="sendCode"
            >{{ time > 0 ? `${time}s后再次发送` : '发送验证码' }}</span
          >
        </template>
      </van-field>
      <div class="cp-cell">
        <van-checkbox v-model="agree">
          <span>我已同意</span>
          <a href="javascript:;">用户协议</a>
          <span>及</span>
          <a href="javascript:;">隐私条款</a>
        </van-checkbox>
      </div>
      <div class="cp-cell">
        <van-button block round type="primary" native-type="submit"
          >登 录</van-button
        >
      </div>
      <div class="cp-cell">
        <a href="javascript:;">忘记密码？</a>
      </div>
    </van-form>
    <!-- 底部 -->
    <div class="login-other">
      <van-divider>第三方登录</van-divider>
      <div class="icon">
        <a
          class="icon"
          :href="qqUrl"
          @click="stores.setReturnUrl($route.query.returnUrl as string)"
        >
          <img src="@/assets/qq.svg" alt="" />
        </a>
        <!-- <span id="qqLoginBtn"></span> -->
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
@import '@/styles/login.scss';
</style>
